package com.zj.config;

import com.zj.i18n.I18nCode;
import com.zj.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class MyResponseBody implements ResponseBodyAdvice {

    @Autowired
    private MessageSource source;
    private static final Logger logger = LoggerFactory.getLogger(MyResponseBody.class);

    @Override
    public Object beforeBodyWrite(Object resBody, MethodParameter arg1, MediaType arg2, Class arg3, ServerHttpRequest req,
                                  ServerHttpResponse res) {
        //resBody就是controller方法中返回的值，对其进行修改后再return就可以了
        System.out.println("haha");
        if (resBody != null && resBody.getClass() == Result.class) {
            Result resBody1 = (Result) resBody;
            I18nCode code = resBody1.getMessageCode();
            String messageNew = resBody1.getMessage();
            if (code != null) {
                messageNew = source.getMessage(code.getMsg(), null, LocaleContextHolder.getLocale());
                resBody1.setMessage(messageNew);
            }

            return resBody1;

        }

        return resBody;
    }

    @Override
    public boolean supports(MethodParameter arg0, Class arg1) {
        //这里直接返回true,表示对任何handler的responsebody都调用beforeBodyWrite方法
        return true;
    }

}
